package com.sec.etech.org.service;

import cn.hutool.core.collection.CollectionUtil;
import org.openbpm.base.api.query.QueryOP;
import org.openbpm.base.core.id.IdUtil;
import org.openbpm.base.core.util.JsonUtil;
import org.openbpm.base.core.util.StringUtil;
import org.openbpm.base.db.model.query.DefaultQueryFilter;
import org.openbpm.org.core.manager.impl.SysResourceManagerImpl;
import org.openbpm.org.core.model.SysResource;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("etechResourceManager")
public class EtechResourceManagerImpl extends SysResourceManagerImpl {

    public void saveAndUpdateTree(SysResource sysResource, String code) {
        if(sysResource==null || StringUtil.isEmpty(sysResource.getId()) || CollectionUtil.isEmpty(sysResource.getChildren())){
            return;
        }
        String parentId = sysResource.getId();

        // 已存在子节点
        Map<String, SysResource> mapExistResources = new HashMap<>();
//        List<SysResource> existChildren = sysResourceDao.getByParentId(parentId);
        DefaultQueryFilter queryFilter = new DefaultQueryFilter();
        queryFilter.addFilter("parent_id_", parentId, QueryOP.EQUAL);
        List<SysResource> existChildren = this.query(queryFilter);
        for(SysResource resource: existChildren){
            mapExistResources.put(resource.getAlias(), resource);
        }

        List<SysResource> children = sysResource.getChildren();
        // 检查增/删/改
        for(int i=0; i<children.size(); i++){
            SysResource child = (SysResource) JsonUtil.parseObject(JsonUtil.toJSONString(children.get(i)), SysResource.class);
            child.setParentId(parentId);
            child.setSn(10*(i+1));
            child.setEnable(1);
            String alias = child.getAlias();
            // 更新
            if(mapExistResources.containsKey(alias)){
                child.setId(mapExistResources.get(alias).getId());
                update(child);
                mapExistResources.remove(alias);
            }else {
                // 新增, 只新增定制按钮，不新增 原有的查询和导出 etech定制
                if(child.getAlias().startsWith("customsql_button_"+code+"_")){
                    child.setId(IdUtil.getSuid());
                    create(child);
                }
            }
        }
        // 逻辑删除剩余记录
        if(!mapExistResources.isEmpty()){
            for(SysResource resource: mapExistResources.values()){
                // 只删除定制按钮和通用的查询和导出
                String alias = resource.getAlias();
                if(("customsql_list_"+code).equals(alias)
                        || ("customsql_export_"+code).equals(alias)
                        || alias.startsWith("customsql_button_"+code+"_")){
                    resource.setEnable(0);
                    update(resource);
                }
            }
        }
    }
}
